package handler

import (
	"context"
	"net/url"
	"strings"

	"github.com/jstang9527/gofor/src/share/config"
	"github.com/jstang9527/gofor/src/share/log"
	"github.com/jstang9527/gofor/src/share/pb"
	"github.com/jstang9527/gofor/src/srv-exploit/payload"
	"github.com/micro/go-micro/errors"
	"go.uber.org/zap"
)

type ExploitServiceExtHandler struct {
	logger *zap.Logger
}

func NewExploitServiceExtHandler() *ExploitServiceExtHandler {
	return &ExploitServiceExtHandler{
		logger: log.Instance(),
	}
}

func (h *ExploitServiceExtHandler) ExploitWithAttack(ctx context.Context, req *pb.ExploitWithAttackReq, rsp *pb.ExploitWithAttackRsp) error {
	// 0.先判断target的参数  (schema://ip:port)
	target := req.Target
	if !strings.HasPrefix(target, "http") {
		target = "http://" + target
	}
	URL, err := url.Parse(req.Target)
	if err != nil {
		h.logger.Error("error", zap.Error(err))
		return errors.New(config.ServiceNameUser, "invalid url target", 200)
	}
	target = "http://" + URL.Host
	// 1.执行CVE
	exploit := payload.NewExploit(req.Cve, target)
	if exploit == nil {
		err := errors.New(config.ServiceNameUser, "unsupport cve-id", 200)
		h.logger.Error("error", zap.Error(err))
		return err
	}
	if err := exploit.Attack(); err != nil {
		h.logger.Error("error", zap.Error(err))
		return errors.New(config.ServiceNameUser, "failed exploit", 200)
	}
	rsp.Tunnel, err = exploit.CreateProxy()
	// 2.返回cve即为成功
	if err == nil {
		rsp.Cve = req.Cve
	}
	return nil
}

func (h *ExploitServiceExtHandler) ExploitWithFlood(ctx context.Context, req *pb.ExploitWithFloodReq, rsp *pb.ExploitWithFloodRsp) error {
	return nil
}

func (h *ExploitServiceExtHandler) GetTaskStatus(ctx context.Context, req *pb.GetTaskStatusReq, rsp *pb.GetTaskStatusRsp) error {
	return nil
}
